/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.designschema.synchronization;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.common.ValueHelpConfig;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.ResourceLocalizeUtil;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.designschema.constant.I18nExceptionConstant;
import com.inspur.edp.web.designschema.constant.I18nMsgConstant;
import com.inspur.edp.web.designschema.elements.Schema;
import com.inspur.edp.web.designschema.synchronization.helplinkconfig.VoMetadataHelpLinkConfigModifierBeforeSaving;
import com.inspur.edp.web.formmetadata.metadata.FormMetadataContent;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FormMetadataUpdate {
    public static void update(GspMetadata formMetadata) {
        FormMetadataContent content = (FormMetadataContent) ((formMetadata.getContent() instanceof FormMetadataContent) ? formMetadata.getContent() : null);
        if (content == null) {
            return;
        }
        String formContent = SerializeUtility.getInstance().serialize(content.getContents());
        JsonNode formObject = null;

        String formString = (formContent instanceof String) ? formContent : null;
        formObject = SerializeUtility.getInstance().toJsonNode(formString);

        JsonNode schemas = null;
        JsonNode jsonNodeModules = formObject.get("module");
        if (jsonNodeModules != null) {
            schemas = jsonNodeModules.get("schemas");
            if (schemas == null) {
                schemas = jsonNodeModules.get("entity");
            }
        }

        if (schemas != null) {
            String schemasString = schemas.toString();

            List<Schema> schemaList = SerializeUtility.getInstance().deserialize(schemasString, new TypeReference<List<Schema>>() {
            });
            Synchronizer synchronizer = new Synchronizer();
            for (Schema schema : schemaList) {
                if ("vo".equals(schema.getSourceType())) {
                    String voPath = StringUtility.getOrDefault(schema.getVoPath(), formMetadata.getRelativePath());
                    String voNameSpace = StringUtility.getOrDefault(schema.getVoNameSpace(), formMetadata.getHeader().getNameSpace());
                    MetadataGetterParameter metadataGetterParameter = MetadataGetterParameter.getNewInstance(schema.getId(), voPath, MetadataTypeEnum.ViewModel);
                    metadataGetterParameter.setTargetMetadataCode(schema.getCode());
                    metadataGetterParameter.setTargetMetadataName(schema.getName());
                    metadataGetterParameter.setTargetMetadataNamespace(voNameSpace);
                    metadataGetterParameter.setTargetMetadataNotFoundMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_DESIGN_SCHEMA_MSG_0005));
                    GspMetadata metadata = MetadataUtility.getInstance().getMetadataWithDesign(metadataGetterParameter);

                    GspViewModel viewObject = (GspViewModel) ((metadata.getContent() instanceof GspViewModel) ? metadata.getContent() : null);
                    if(viewObject == null){
                        continue;
                    }

                    GspViewModel clonedViewObject = SerializeUtility.getInstance().deserialize(SerializeUtility.getInstance().serialize(viewObject), GspViewModel.class);

                    // 根据当前表单更新ViewObject
                    GspViewModel gspViewModel = synchronizer.synchronize(formObject, schema, viewObject);

                    // 添加关联的表单的帮助配置
                    JsonNode refFormObject = getRefFormObject(formObject, formMetadata.getRelativePath());
                    if(refFormObject != null){
                        JsonNode refSchemaNode = refFormObject.at("/module/schemas/0");
                        String refSchemaString = refSchemaNode.toString();
                        Schema refSchema = SerializeUtility.getInstance().deserialize(refSchemaString,Schema.class);
                        GspViewModel refGspViewModel = synchronizer.synchronize(refFormObject, refSchema, clonedViewObject);

                        // 合并帮助配置
                        mergeHelpConfig(gspViewModel,refGspViewModel);
                    }

                    metadata.setContent(gspViewModel);

                    // 执行元数据保存前参数处理 action
                    VoMetadataHelpLinkConfigModifierBeforeSaving.modify(metadata);

                    MetadataService service = SpringBeanUtils.getBean(MetadataService.class);
                    service.saveMetadata(metadata, metadata.getRelativePath() + "/" + metadata.getHeader().getFileName());
                }
            }
        } else {
            throw new WebCustomException(I18nExceptionConstant.WEB_DESIGN_SCHEMA_ERROR_0008);
        }
    }

    private static JsonNode getRefFormObject(JsonNode formObject,String relativePath) {
        JsonNode refMetadataIdNode = formObject.at("/options/mobileMetadataId");
        if(refMetadataIdNode == null || refMetadataIdNode.isMissingNode()){
            refMetadataIdNode = formObject.at("/options/pcMetadataId");
        }
        if(refMetadataIdNode == null || refMetadataIdNode.isMissingNode()){
            return null;
        }

        String refMetadataId = refMetadataIdNode.asText() ;
        if(StringUtility.isNullOrEmpty(refMetadataId)){
            return null;
        }
        MetadataGetterParameter refMetadataGetterParameter = MetadataGetterParameter.getNewInstance(refMetadataId, relativePath, MetadataTypeEnum.Frm);

        GspMetadata refMetadata = null;

        try {
            refMetadata = MetadataUtility.getInstance().getMetadataWithDesign(refMetadataGetterParameter);
        } catch (Exception e) {
            //忽略异常
            WebLogger.Instance.error(e);
        }

        if(refMetadata == null){
            return null;
        }
        FormMetadataContent refFormContent = (FormMetadataContent)refMetadata.getContent();
        JsonNode refFormObject = refFormContent.getContents();

        JsonNode schemasNode = formObject.at("/module/schemas/0");
        JsonNode refSchemasNode = refFormObject.at("/module/schemas/0");
        if (schemasNode == null || refSchemasNode == null) {
            return null;
        }

        String voId = schemasNode.get("id").asText();
        String refVoId = refSchemasNode.get("id").asText();
        if(!voId.equals(refVoId)){
            return null;
        }

        return refFormObject;
    }

    private static void mergeHelpConfig(GspViewModel gspViewModel, GspViewModel refGspViewModel){
        ArrayList<ValueHelpConfig> valueHelpConfigs = gspViewModel.getValueHelpConfigs();
        ArrayList<ValueHelpConfig> refValueHelpConfigs = refGspViewModel.getValueHelpConfigs();

        // 创建现有帮助配置ID的集合
        Set<String> existingConfigIds = valueHelpConfigs.stream()
                .map(ValueHelpConfig::getElementId)
                .collect(Collectors.toSet());

        // 过滤出需要添加的帮助配置
        List<ValueHelpConfig> configsToAdd = refValueHelpConfigs.stream()
                .filter(config -> !existingConfigIds.contains(config.getElementId()))
                .collect(Collectors.toList());

        // 批量添加新的帮助配置
        valueHelpConfigs.addAll(configsToAdd);
    }

}
